package com.hengfoxwolf.commonbase.base.adapter
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView

abstract class BaseRvMultiTypeAdapter<H : ViewDataBinding, B : ViewDataBinding,F : ViewDataBinding>(
    headerLayoutMethod: (LayoutInflater, ViewGroup, Boolean) -> H,
    bodyLayoutMethod: (LayoutInflater, ViewGroup, Boolean) -> B,
    footerLayoutMethod: (LayoutInflater, ViewGroup, Boolean) -> F,
) : RecyclerView.Adapter<BaseRvMultiTypeAdapter<H, B,F>.ViewHolder>() {

    private val mHeaderLayoutMethod = headerLayoutMethod
    private val mLayoutMethod = bodyLayoutMethod
    private val mFooterLayoutMethod = footerLayoutMethod
    protected var mContext: Context? = null

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        lateinit var binding: ViewDataBinding
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        if (mContext == null) {
            mContext = parent.context
        }
        if (HEAD_FLAG == viewType) {
            val binding: H = mHeaderLayoutMethod.invoke(LayoutInflater.from(mContext), parent, false)
            val holder = ViewHolder(binding.root)
            holder.binding = binding
            return holder
        } else if (BODY_FLAG == viewType) {
            val binding: B = mLayoutMethod.invoke(LayoutInflater.from(mContext), parent, false)
            val holder = ViewHolder(binding.root)
            holder.binding = binding
            return holder
        } else {
            val binding: F =
                mFooterLayoutMethod.invoke(LayoutInflater.from(mContext), parent, false)
            val holder = ViewHolder(binding.root)
            holder.binding = binding
            return holder
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.executePendingBindings()
        bindData(holder, position)
    }

    override fun getItemCount(): Int = 3

    override fun getItemViewType(position: Int): Int {
        return if (position == 0) HEAD_FLAG else if (position == 1) BODY_FLAG else FOOT_FLAG
    }

    abstract fun bindData(holder: ViewHolder,position: Int)

    companion object {
        const val TAG = "BaseRvMultiTypeAdapter"
        const val HEAD_FLAG = 0x00
        const val BODY_FLAG = 0x01
        const val FOOT_FLAG = 0x02
    }
}